<template>
  <div>
    <van-dialog
      ref="myDialog"
      title="新增批次"
      className="myDialog"
      v-model="isShow"
      :before-close="beforClose"
      show-cancel-button
      confirm-button-color="#518CF6"
      @cancel="handleCancel"
      @confirm="handleConfirm"
    >
      <div class="modal-container">
        <el-form
          ref="addBatchForm"
          :model="form"
          label-width="80px"
          :rules="rules"
          @submit.native.prevent
        >
          <el-form-item label="批次号" prop="barCode">
            <el-input size="mini" disabled  v-model="form.barCode"></el-input>
          </el-form-item>
          <el-form-item label="物料名称" prop="materialName">
            <el-select
              size="mini"
              style="width: 100%"
              v-model="form.materialName"
              @change="handleChange"
              v-loadData="loadData"
              :loading="loading"
              filterable
              remote
              :disabled="isLock"
              :remote-method="remoteMethod"
            >
              <el-option
                v-for="item in materialOptions"
                :key="item.code"
                :label="item.name"
                :value="item.code"
              >
                <div class="myOption">
                  <span class="myOption-l"
                    >{{ item.name }}|{{ item.code }}</span
                  >
                  
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="特征参数" prop="skuName">
            <el-input
              size="mini"
              readonly
              :disabled="isLock"
              v-model="form.skuName"
              @focus="skuDialog()"
            ></el-input>
          </el-form-item>
          <el-form-item label="实际数量" prop="realNum">
            <el-input size="mini" v-model="form.realNum" type="number"></el-input>
          </el-form-item>
          <el-form-item label="批次品质" prop="materialQuality">
            <el-select
              v-model="form.materialQuality"
              style="width: 100%"
              size="mini"
            >
              <el-option
                v-for="item in materialQualityOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </van-dialog>

    <!--物料特征参数选择弹窗 -->
    <ChoiceSpecificParamsDialog
      v-if="choiceSpecificParamstVisible"
      :show="choiceSpecificParamstVisible"
      :material-code="skuData.code"
      :sku-id="skuData.skuId"
      @confirm="confirmChoiceSpecificParams"
      @cancel="cancelChoiceSpecificParams"
    />
  </div>
</template>
<script>
import ChoiceSpecificParamsDialog from "@/components/ChoiceSpecificParamsDialog/index.vue";
import {
  materialsList,
  newAddBarCode,
  getNewAddBarCodeProgress,
  addMaterialDetails,
  getWorkerOrderCodeList,
} from "@/api/inventory";
import { Toast } from "vant";
import Vue from "vue";
Vue.directive("loadData", {
  bind(el, binding) {
    // 获取element-ui定义好的scroll盒子
    const SELECTWRAP_DOM = el.querySelector(
      ".el-select-dropdown .el-select-dropdown__wrap"
    );
    SELECTWRAP_DOM.addEventListener("scroll", function () {
      /**
       * scrollHeight 获取元素内容高度(只读)
       * scrollTop 获取或者设置元素的偏移值,常用于, 计算滚动条的位置, 当一个元素的容器没有产生垂直方向的滚动条, 那它的scrollTop的值默认为0.
       * clientHeight 读取元素的可见高度(只读)
       * 如果元素滚动到底, 下面等式返回true, 没有则返回false:
       * ele.scrollHeight - ele.scrollTop === ele.clientHeight;
       */
      const condition =
        this.scrollHeight - this.scrollTop <= this.clientHeight + 10;
      //监听下拉框是否滚动到底部，滚动到底部就加载下一页数据
      if (condition) binding.value();
    });
  },
});
export default {
  data() {
    let validateRealNum = (rule, value, callback)=>{
      if (!value) {
        return callback(new Error('实际数量必须为大于0的数字'));
      }else if(value < 0){
        return callback(new Error('实际数量必须为大于0的数字'));
      }else{
        callback();
      }
    }
    return {
      form: {
        barCode:"",
        skuName:""
      },
      rules: {
        barCode: { required: true, message: "请输入批次号", trigger: "blur" },
        materialName: {
          required: true,
          message: "请选择物料",
          trigger: "blur",
        },
        // skuName: {
        //   required: true,
        //   message: "请选择特征参数",
        //   trigger: ["blur", "change"],
        // },
        realNum: { required: true,  trigger: "blur" ,validator: validateRealNum},
        materialQuality: {
          required: true,
          message: "请选择批次品质",
          trigger: "blur",
        },
      },
      materialOptions: [],
      materialQualityOptions: [
        {
          value: "1",
          label: "合格",
        },
        {
          value: "0",
          label: "不合格",
        },
      ],
      choiceSpecificParamstVisible: false,
      skuData: {},
      searchParms: {
        current: 1,
        size: 10,
        states: "2",
        isBatchMag:true
      },
      finished: false, // 是否加载完所有数据
      scrollLoading: false,
      loading: false,
    };
  },
  components: { ChoiceSpecificParamsDialog },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    warehouseCode: {
      type: String,
      default: "",
    },
    barCode: {
      type: String,
      default: "",
    },
    skuObj:{
      type:Object,
      default:()=>{
        return{}
      }
    },
    materialName:{
      type:String,
      default:""
    },
    materialCode:{
      type:String,
      default:""
    },
    orderNumber:{
      type:String,
      default:""
    },
    isLock:{
      type: Boolean,
      default: false,
    }
  },
  computed: {
    isShow: {
      get() {
        return this.show;
      },
      set(val) {
        this.$emit("update:show", !this.show);
      },
    },
  },
  async created() {
    await this.getData();
    this.form.barCode = this.barCode;
    if(this.materialCode || this.skuObj.skuId){
      this.form.materialCode = this.materialCode
      this.form.materialName = this.materialName
      this.skuData.code = this.materialCode
      this.form.productCode = this.materialCode
      this.skuData.skuId = this.skuObj.skuId
      this.form.skuName = this.skuObj.skuName
    }
    
  },
  
  methods: {
    loadData() {
      let timeout = null;
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        if (this.finished) return;
        if (this.scrollLoading) return;
        this.searchParms.current += 1;
        this.getData();
      }, 500);
    },
    async getData() {
      this.scrollLoading = true;
      const result = await materialsList(this.searchParms);
      const { code, data, message } = result.data;
      this.scrollLoading = false;
      if (code == 200) {
        // this.materialOptions = data.records;
        if (this.searchParms.current > 1) {
          this.materialOptions = [...this.materialOptions, ...data.records];
        } else {
          this.materialOptions = data.records;
        }
        if (this.materialOptions.length == data.total) {
          this.finished = true;
        }
      }
      return this.materialOptions
    },
    async remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        this.searchParms.name = query;
        this.searchParms.current = 1;
        await this.getData();
        this.loading = false;
      }
    },
    beforClose(action, done) {
      if (action == "confirm") {
        this.$refs.addBatchForm.validate(async (valid) => {
          if (valid) {
            try {
              await this.addBatchForm(done);
              
              
            } catch (error) {
              Toast.fail(error.message)
              done(false);
            }
            
          } else {
            done(false);
          }
        });
      } else {
        done();
      }
    },
    handleConfirm() {},
    async addBatchForm(done) {
      return new Promise(async (resolve, reject) => {
        try {
          const params = this.addBatchFormParms();
          const result = await newAddBarCode(params);
          const { code, data, message } = result.data;
          if (code == 200) {
            const reject = await this.getNewAddBarCodeProgress(this.orderNumber);
            const confirmParams = {
              records:reject,
              form:this.form
            }
            this.$emit("handleConfirm",confirmParams,done);
            resolve()
          }
        } catch (error) {
          reject(error)
        }
      });
    },
    
    
    async getNewAddBarCodeProgress(orderNumber) {
      const result = await getNewAddBarCodeProgress({
        relatedNumber: orderNumber,
        type: "otherInStockBatch",
      });
      const { data, code, message } = result.data;
      let rejectData = []
      if (code == 200) {
        const {
          progress,
          executionDescription,
          code: innnerCode,
          executionStatus,
        } = JSON.parse(message);
        if (innnerCode == "200") {
          if (executionStatus) {
            rejectData = this.getBatchCodeList();
          } else {
            await this.getNewAddBarCodeProgress(orderNumber);
          }
        } else {
          throw new Error(executionDescription || "批次新增异常！");
        }
        return rejectData
      }
    },
    // 新增完成后获取批次信息
    async getBatchCodeList() {
      const {
        data: {
          code,
          data: { records = [] },
        },
      } = await getWorkerOrderCodeList({
        current: 1,
        size: 99999,
        materialCode: this.form.productCode,
        relateNumber: this.orderNumber,
        // skuId: this.formData?.skuId || 0,
      });
      if (code === "200") {
        return records
        
      }else{
        return []
      }
    },
    addBatchFormParms() {
      let orderNumber = this.orderNumber; // 入库单号
      let supplierCode = "";
      let relateOrders = ""; //关联单号
      const param = {
        skuId: this.form.skuId || 0,
        batchSpecs: this.form.batchSpecs || "", // 批次规格
        batchCount: 1,
        barCode: this.form.barCode,
        count: this.form.realNum,
        num: 1,
        relateNumber: orderNumber,
        materialCode: this.form.productCode,
        numberRuleId: "154",
        ruleDetail:
          '[{"type":1,"code":1,"name":"人工输入","rule":"","value":"531","seq":null,"autoIncrementConfigureType":null,"uuid":null}]',
        supplierCode,
        numberMap: {
          6: this.form.productCode ?? "",
          12: supplierCode ?? "",
          13: relateOrders,
          15: orderNumber,
        },
        relatedMap: {
          supplier: supplierCode ?? "",
          purchase: relateOrders,
          purchaseReceipt: orderNumber,
        },
        moduleType: "otherInStockBatch",
        remarks: "",
      };
      return param;
    },
    handleCancel() {
      this.$emit("handleCancel");
    },
    handleChange(val) {
      const array = this.materialOptions.filter(item => item.code === val)
      this.skuData.code = val;
      this.form.productCode = val;
      this.form.materialName = val;
      this.form.materialType = array[0].typeName;
      this.form.type = array[0].type;
      console.log('this.form',this.form)
    },
    skuDialog() {
      if (!this.skuData.code) {
        Toast("请先选择物料");
        return;
      }
      this.choiceSpecificParamstVisible = true;
    },
    confirmChoiceSpecificParams(data) {
      this.skuData.skuId = data.skuId;
      this.skuData.skuCode = data.skuCode;
      this.skuData.skuName = data.skuName;
      this.form.skuId = data.skuId;
      this.form.skuCode = data.skuCode;
      this.form.skuName = data.skuName;
      this.choiceSpecificParamstVisible = false;
    },
    cancelChoiceSpecificParams() {
      this.choiceSpecificParamstVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-form-item{
  margin-bottom: 5px;
  .el-form-item__error{
    top:80%
  }
}

.modal-container {
  padding: 5px 15px;
}
.el-select-dropdown__item{
  width: 300px;
  height: auto;
  min-height: 34px;
}
.myOption {
  display: flex;
  justify-content: space-between;
  .myOption-l {
    margin-right: 15px;
    word-break:break-all;
    white-space:normal;
  }
}
</style>